package jp.bgbt.fles.app.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.common.utils.LogUtil;
import com.common.utils.StringUtils;

import java.util.UUID;

import androidx.annotation.Nullable;
import jp.bgbt.fles.app.bean.StrategyDetailsBean;

public class BleService extends Service implements BleConnectCallBack.OnBleConnectListener{

    private String TAG = getClass().getSimpleName();

    private final IBinder mBinder = new LocalBinder();
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;
    private BleConnectCallBack callBack;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private void startNotification(String serviceUUID, String charaterUUID) {
        BluetoothGattCharacteristic c1 = getCharacter(serviceUUID, charaterUUID);
        if (c1 != null) {
            // Log.e("taa","获取到了通知");
            final int cx1 = c1.getProperties();
            if ((cx1 | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                // 如果有一个活跃的通知上的特点,明确第一所以不更新用户界面上的数据字段。
                if (c1 != null) {
                    // Log.e("error","设置0为false");
                    setCharacteristicNotification(c1, false);
                }
                readCharacteristic(serviceUUID, charaterUUID);
                if ((cx1 | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                    // Log.e("error","继续清理1");
                    setCharacteristicNotification(c1, true);
                }
            }
        }
    }

    /**
     * 读取特征值的Values
     */
    public void readCharacteristic(String service_uuid, String cha_uuid) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            return;
        }
        BluetoothGattCharacteristic c1 = getCharacter(service_uuid, cha_uuid);
        if (c1 != null) {
            mBluetoothGatt.readCharacteristic(c1);
        }
    }

    public void setCharacteristicNotification(
            BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (mBluetoothAdapter == null) {
            // Log.e("error", "BluetoothAdapter not initialized");
            return;
        }
        // Log.e("taa","开启了广播");
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID
                .fromString(BleConstant.DES_UUID1));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        if (mBluetoothGatt != null) {
            mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        }
        if (mBluetoothGatt != null)
            mBluetoothGatt.writeDescriptor(descriptor);
    }

    @Override
    public void onConnected(String mac) {
        BleDeviceInfo.getInstance().init(mac);
        LogUtil.e("设备连接成功");
        mBluetoothGatt.discoverServices();
    }

    @Override
    public void onBleServiceDiscovered() {
        startNotification(BleConstant.SERVICE_UUID1, BleConstant.CHA_UUID1);
        BleCommandUtil.getInstance().sendReadDeviceInfoData();
    }

    @Override
    public void onDisConnected() {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();// 3.15新增，解决status 133的问题
            mBluetoothGatt = null;
        }
    }

    public class LocalBinder extends Binder {
        public BleService getService() {
            return BleService.this;
        }
    }


    public void connect(String mac){
        StrategyDetailsBean.getInstance().setDeviceId(mac);
        if(callBack == null)
            callBack = new BleConnectCallBack(this);
        if (StringUtils.isEmpty(mac)) {
            LogUtil.d("connect ble with MAC null");
            return;
        }
        if(initialize()) {
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac.toUpperCase().trim());
            if(device == null) {
                LogUtil.d("Device not found");
                return;
            }
            if (mBluetoothGatt != null) {
                mBluetoothGatt.close();// 3.15新增，解决status 133的问题
                mBluetoothGatt = null;
            }
            mBluetoothGatt = device.connectGatt(this, false, callBack);
        } else {
            LogUtil.d("ble init falied");
        }
    }

    private boolean initialize() {
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                LogUtil.d("Unable to initialize BluetoothManager.");
                return false;
            }
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        return mBluetoothAdapter != null;
    }

    public synchronized boolean writeLlsAlertLevel(String service_uuid, String cha_uuid, byte[] bb) {
        StringBuffer b = new StringBuffer();
        for (int i = 0; i < bb.length; i++) {
            b.append(String.format("%02X ", bb[i]).toString().trim());
        }
        String string = b.toString();
//        LogUtil.e("发动的驱动是:" + string);
        BluetoothGattCharacteristic alertLevel = getCharacter(service_uuid,
                cha_uuid);
        if (alertLevel == null) {
            // Log.e("error","link loss Alert Level charateristic not found!");
            return false;
        }
        boolean status = false;
        alertLevel.setValue(bb);
        alertLevel.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
        if (mBluetoothGatt != null) {
            status = mBluetoothGatt.writeCharacteristic(alertLevel);
        }
        return status;
    }

    public BluetoothGattCharacteristic getCharacter(String serviceUUID,
                                                    String characterUUID) {
        // Log.e("error","设备名称："+mBluetoothGatt.getDevice().getAddress());
        if (mBluetoothGatt == null) {
            return null;
        }
        BluetoothGattService service = mBluetoothGatt.getService(UUID
                .fromString(serviceUUID));
        if (service != null) {
            return service.getCharacteristic(UUID.fromString(characterUUID));
        }
        return null;
    }

}
